jQuery.noConflict();
angular.module('mainApp', []). config(function($routeProvider) {
	$routeProvider.
		when('/', {controller:UploadViewController, templateUrl:'views/uploadView.html'}).
		when('/detection/:userId', {controller:DetectionViewController, templateUrl:'views/detectionView.html'}).
		otherwise({redirectTo:'/'});
});

function UploadViewController($scope) {
	
}

function DetectionViewController($scope, $routeParams, $http) {
	// Randomizing to prevent caching of picture
	$scope.pictureLocation = 'upload/' + $routeParams.userId + '/face.jpg?' + Math.random(100000);
	$scope.shouldShowCompareButton = true;
	$scope.shouldDisplayMissingLandmarkInput = false;
	$scope.algorithmType = "p";
	$scope.limit = 0.5;
	
	var canvas = document.getElementById("drawingCanvas");
	$scope.context = canvas.getContext("2d");
	
	var image = new Image();
	image.onload = function() {
		var canvas = document.getElementById("drawingCanvas");
		canvas.width = image.width;
		canvas.height = image.height;
		$scope.context.drawImage(image, 0, 0);
	}
	image.src = $scope.pictureLocation;	
	
	$scope.canvasOnClick = function(event) {
		if ($scope.shouldDisplayMissingLandmarkInput && $scope.nextToAddLandmark < $scope.missingLandmarks.length) {
			var x = event.pageX - canvas.offsetLeft;
			var y = event.pageY - canvas.offsetTop;
			
			$scope.context.beginPath();
			$scope.context.lineWidth = 1;
			$scope.context.strokeStyle = 'blue';
			$scope.context.fillStyle = 'blue';
			$scope.context.arc(x, y, 3, 0, 2 * Math.PI, false);
			$scope.context.stroke();
			$scope.context.fill();
			$scope.context.closePath();
			$scope.missingLandmarks[$scope.nextToAddLandmark].selected = true;
			$scope.missingLandmarks[$scope.nextToAddLandmark].location.x = x;
			$scope.missingLandmarks[$scope.nextToAddLandmark].location.y = y;
			
			$scope.nextToAddLandmark++;
		}
	}
	
	$scope.saveLandmarksAndCompare = function() {
		if ($scope.nextToAddLandmark >= $scope.missingLandmarks.length) {
			$http({
			            url: 'server_scripts/save_landmarks.php',
			            method: "POST",
			            data: 'missingData=' + JSON.stringify($scope.missingLandmarks),
			            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
			        }).success(function(data) {
				// Hide missing landmark input
				$scope.shouldDisplayMissingLandmarkInput = false;

				// Compare faces
				$scope.compareFace();
			});
		}
		else {
			alert("Enter all missing landmarks before completing this operation!");
		}
	}
	
	$scope.compareFace = function() {
		$http.get('server_scripts/compare_faces.php?algorithmType=' + $scope.algorithmType + '&percent=' + $scope.limit).success(function(data) {
			var array = new Array(data.length);
			var i = 0;
			for (var key in data) {
				var obj = new Object();
				obj.image = key + "?" + Math.random(10000);
				obj.compareValue = Math.round(data[key] * 100);
				array[i++] = obj;
			}
			$scope.similarFaces = array;
			$scope.shouldDisplaySimilar = true;
		});
	}
	
	$scope.faceDetector = function() {
		$scope.shouldShowCompareButton = false;
		$scope.landmarkNames = ['Forehead', 'Chin', 'Middle of eyes', 'Left eye left point', 'Left eye right point',
								'Right eye left point', 'Right eye right point', 'Nose left point', 'Nose middle point',
								'Nose right point', 'Mouth left point', 'Mouth right point','',''];
		$http.get('server_scripts/detect_face.php').success(function(data) {
			for(i=0;i<data.length;i++) {
				var face = data[i];

				$scope.context.beginPath();
				$scope.context.strokeStyle = '#F00';
				$scope.context.lineWidth = 3;
				$scope.context.strokeRect(face[0],face[1],face[2] - face[0], face[3] - face[1]);
				$scope.context.closePath();
			}
			
			$http.get('server_scripts/detect_landmarks.php').success(function(data) {
				var array = null;
				if (data instanceof Array) {
					array = data;
				}
				else {
					array = new Array(1);
					array[0] = data;
				}
				
				var numberOfLocated = 0;
				for (i = 0;i < array.length;i++) {
					var face = array[i];
					$scope.locatedLandmarkTypes = new Array(face.landmark.length);
					for (j = 0;j < face.landmark.length;j++) {
						var landmark = face.landmark[j];

						$scope.context.beginPath();
						$scope.context.lineWidth = 1;
						$scope.context.strokeStyle = 'blue';
						$scope.context.fillStyle = 'blue';
						$scope.context.arc(landmark.x, landmark.y, 3, 0, 2 * Math.PI, false);
						$scope.context.stroke();
						$scope.context.fill();
						$scope.context.closePath();
						$scope.locatedLandmarkTypes[landmark.type_id] = true;
						numberOfLocated++;
					}
				}

				if (numberOfLocated < 14) {
					var numberOfMissing = 14 - $scope.locatedLandmarkTypes.length;
					$scope.missingLandmarks = new Array(numberOfMissing);
					var k = 0;
					for (var i = 0; i < 14; i++) {
						if ($scope.locatedLandmarkTypes[i] !== true) {
							var obj = new Object();
							obj.selected = false;
							obj.name = $scope.landmarkNames[i];
							obj.location = new Object();
							obj.location.x = -1;
							obj.location.y = -1;
							obj.type_id = i;
							$scope.missingLandmarks[k++] = obj;
						}
					}
					$scope.nextToAddLandmark = 0;
					$scope.shouldDisplayMissingLandmarkInput = true;
				}
				else {
					$scope.compareFace();
				}
			});
		});
	}
}